﻿#include "global.h"
#ifndef __CTEXTURE_H__
#define __CTEXTURE_H__


#include <d3d9.h>
#include <d3dx9.h>




class CTexture {

public:
	char* FileName; //đường dẫn tới file ảnh
	RECT Size;		//độ phân giải ảnh
	LPDIRECT3DTEXTURE9 Texture;
	int Cols;		//số cột frame
	int Rows;		//số hàng frame
	int Count;		//tổng số frame
	int FrameWidth;		//width of 1 frame
	int FrameHeight;	//height of 1 frame

	CTexture(char* _fileName, int cols = 1, int rows = 1, int count = 1){
		Cols = cols;
		Rows = rows;
		Count = count;
		FileName = _fileName;
		this->Load();
	}

	~CTexture(){
		if(this->Texture != NULL){
			this->Texture->Release();
		}
	}
	
	//vẽ texture tại vị trí (x, y) trên màn hình
	void Draw(int x, int y) {
		D3DXVECTOR3 position((float)x, (float)y, 0);
		G_SpriteHandler->Draw( Texture, &Size, NULL, &position, 0xFFFFFFFF );
	}

	//vẽ 1 phần texture tại vị trí (x, y)
	void DrawRect(int x, int y, RECT srcRect) {
		D3DXVECTOR3 position((float)x, (float)y, 0);
		G_SpriteHandler->Draw( Texture, &srcRect, NULL, &position, 0xFFFFFFFF);
	}

private:
	void Load(){
		D3DXIMAGE_INFO info; 
		HRESULT result;

		result = D3DXGetImageInfoFromFile(FileName, &info);

		RECT s = {0, 0, info.Width, info.Height};
		this->Size = s;

		FrameWidth = info.Width / Cols;
		FrameHeight = info.Height / Rows;

		if (result != D3D_OK)
		{
			GLMessage("Can not load texture");
			GLTrace("[texture.h] Failed to get information from image file [%s]", FileName);
			OutputDebugString(FileName);
			return;
		}

		result = D3DXCreateTextureFromFileEx(
			G_Device,
			FileName,
			info.Width,
			info.Height,
			1,
			D3DUSAGE_DYNAMIC,
			D3DFMT_UNKNOWN,
			D3DPOOL_DEFAULT,
			D3DX_DEFAULT,
			D3DX_DEFAULT,
			0, //color
			&info,
			NULL,
			&Texture
			);

		if (result != D3D_OK) 
		{
			GLMessage("Can not load texture");
			GLTrace("[texture.h] Failed to create texture from file '%s'", FileName);
			return;
		}
	}

};


#endif